package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.User;
import net.zjitc.utils.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    JdbcTemplate template=new JdbcTemplate(JdbcUtils.getDataSource());
    @Override
    public List<User> findAll() {
        String sql="select * from user";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<User>(User.class));
        return list;
    }

    @Override
    public User findById(String id) {
        String sql="select * from user where id=?";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<User>(User.class),id);
        if (list.size()==0){
            return null;
        }
        if(list.size()==1){
            return list.get(0);
        }
        return null;
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
        String sql="select * from user where username=? and password=?";
        List<User> list=template.query(sql,new BeanPropertyRowMapper<User>(User.class),username,password);
        if (list.size()==0){
            return null;
        }
        if(list.size()==1){
            return list.get(0);
        }
        return null;
    }

    @Override
    public int add(User user) {
        String sql="insert into user(username, password, sex, email, tel) values(?, ?, ?, ?, ?)";
        return template.update(sql, user.getUsername(), user.getPassword(), user.getSex(), user.getEmail(), user.getTel());
    }

    @Override
    public int update(User user) {
        String sql="update user set username=?, password=?, sex=?, email=?, tel=? where id=?";
        return template.update(sql, user.getUsername(), user.getPassword(), user.getSex(), user.getEmail(), user.getTel(), user.getId());
    }

    @Override
    public int delete(int id) {
        String sql="delete from user where id=?";
        return template.update(sql, id);
    }
}
